import React from 'react';
import { Table, ConfigProvider } from 'antd';
import produce from 'immer';
import { formatMessage } from 'umi';

const Index = (props) => {
  const {
    rowKey = null, // 动态识别rowKey
    columns = [],
    dataSource = [],
    pagination = false,

    lazyPagination = true,

    ...rest
  } = props;

  const newRowKey =
    typeof rowKey === 'function'
      ? rowKey
      : rowKey || (dataSource.some((item) => item.key) ? 'key' : 'id');

  const newPagination = produce(pagination, (draftState) => {
    if (draftState !== false) {
      draftState = {
        showSizeChanger: true,
        showQuickJumper: true,
        size: 'small',
        ...draftState,
      };

      if (lazyPagination) {
        const newPageSize = Object.keys(draftState).includes('pageSize')
          ? draftState.pageSize
          : draftState.defaultPageSize;
        if (draftState.total <= newPageSize) {
          draftState = false;
        }
      }
    }
    return draftState;
  });

  return (
    <ConfigProvider
      renderEmpty={() => (
        <div style={{ textAlign: 'center' }}>{formatMessage({ id: '暂无数据' })}</div>
      )}
    >
      <Table
        defaultExpandAllRows={true}
        rowKey={newRowKey}
        columns={columns}
        dataSource={dataSource}
        {...rest}
        pagination={newPagination}
      />
    </ConfigProvider>
  );
};

Object.keys(Table).forEach((item) => {
  if (!['defaultProps'].includes(item)) {
    Index[item] = Table[item];
  }
});
Index.displayName = 'Table';
export default Index;
